package lh.chatroom.service.impl;

import lh.chatroom.domain.Member;
import lh.chatroom.domain.Role;
import lh.chatroom.domain.Room;
import lh.chatroom.repository.MemberRepository;
import lh.chatroom.service.IMemberService;
import lh.chatroom.service.IRoleService;
import lh.chatroom.service.IRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * Created by lh on 2016/7/16.
 */
@Service
public class MemberServiceImpl implements IMemberService {
    @Autowired
    private MemberRepository memberRepository;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoomService roomService;

    @Override
    public Member create(Member member) {
        String roleId = member.getRole().getId();
        Optional<Role> roleOptional = roleService.getById(roleId);
        if (roleOptional.isPresent()) {
            member.setRole(roleOptional.get());
        }

        Member newMember = memberRepository.save(member);

        String roomId = member.getRoom().getId();
//        Optional<Room> roomOptional = roomService.getById(roomId);
//        roomOptional.ifPresent(room -> {
//            room.getMembers().add(newMember);
//            roomService.update(room);
//        });
        return newMember;
    }

    @Override
    public Optional<Member> getById(String id) {
        return Optional.ofNullable(memberRepository.findOne(id));
    }

    @Override
    public void delete(Member member) {
        member.getRoom().getMembers().remove(member);
        roomService.update(member.getRoom());
        memberRepository.delete(member);
    }

    @Override
    public Member update(Member member) {
        return memberRepository.save(member);
    }
}
